import wepy from 'wepy';

/**
 * 拆包查询前缀
 * 首先查找_this传递过来的this页面下是否有url页面,有则返回false
 * @param {object} _this 传入当前的 this 对象
 * @param {string} url 需要跳转的url
*/
function analysisUrl(_this, url) {
  for (let i = 0; i < _this.$parent.config.pages.length; i++)
    if (_this.$parent.config.pages[i].indexOf(url) != -1)
      return false;

  for (let i = 0; i < _this.$parent.config.subPackages.length; i++)
    for (let j = 0; j < _this.$parent.config.subPackages[i].pages.length; j++)
      if (_this.$parent.config.subPackages[i].pages[j] == url)
        return _this.$parent.config.subPackages[i].name
}
/**
 * @param {object} _this 传入当前 object this
 * @param {string} url 跳转的 url 
 * @param {object} objectData 携带参数
 * @param {number} type 0.为默认新页面打开 1.为当前页面打开
*/
function pageJump(_this, url, objectData = {}, type = 0) {
  // console.log(_this, url, objectData, type);
  // 获取传递过来的url页面路径
  let currentUrl = getCurrentPages()[getCurrentPages().length - 1].route
  let targetparentUrl = this.analysisUrl(_this, url);   // 启动analysisUrl,有页面则返回false
  let urlText = "";
  let bannerList = ['index', 'class', 'userPage'];
  let indexOfUrl = bannerList.indexOf(url)  // 判断url是否为根目录下页面,是则返回true
  if (!targetparentUrl && !indexOfUrl) { // 返回更目录
    type = 1;
    if (currentUrl.split('/').length == 3) {
      urlText += '../' + url
    }
    else if (currentUrl.split('/').length == 2) {
      urlText += './' + url
    }
  }
  else {
    if (currentUrl.indexOf(targetparentUrl) == -1) {
      if (currentUrl.split('/').length == 3) {
        urlText += '../' + (targetparentUrl == false ? '' : '/') + url;
      }
      else {
        urlText += './' + targetparentUrl + (targetparentUrl == false ? '' : '/') + url;
      }
    }
    else {
      urlText += './' + url;
    }
  }

  // urlText += '?userid=' + this.getUserid();

  //
  // for (let item in objectData) {
  //   urlText += '&' + item + '=' + objectData[item];
  // }
  // objectData.userid = this.getUserid();

  // console.log(type)
  console.log(urlText)

  if (type == 0) {
    _this.$preload('data', objectData)
    wepy.navigateTo({
      url: urlText
    });
  } else if (type == 1) {
    _this.$preload('data', objectData)
    wepy.redirectTo({
      url: urlText
    });
  }
}

/**
 * 用户获得数据
 * @param {object} _this 传入当前 object this
 * @param {string} url 跳转的 url 
 * @param {object} objectData 携带参数
 * @param {number} type 0.为默认新页面打开 1.为当前页面打开
*/
function get(url, getDate = {}) {
  getDate.userid = getUserid();
  getDate.token = getToken();
  return new Promise((resolve, reject) => {
    wx.request ({
      url: url,
      data: getDate,
      method: 'GET',
      // header: {}, // 设置请求的 header 默认是application/json 
      complete: function (res) {
        resolve(res);
      }
    });
  });
}
function getUserid() {
  return wx.getStorageSync('userid') == '' ? 0 : wx.getStorageSync('userid');
}
function getToken() {
  return wx.getStorageSync('token') == '' ? 0 : wx.getStorageSync('token');
}
// 获取当前时间
function getCurrentTime() {
  let keep = ''
  let date = new Date()
  let y = date.getFullYear()
  let m = date.getMonth() + 1
  m = m < 10 ? '0' + m : m
  let d = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  let h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
  let f = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  keep = y + '' + m + '' + d + '' + h + '' + f + '' + s
  return keep // 20160614134947
}








function objLength(input) {
  let type = toString(input)
  let length = 0
  if (type !== '[object Object]') {
    // throw '输入必须为对象{}！'
  } else {
    for (let key in input) {
      if (key !== 'number') {
        length++
      }
    }
  }
  return length
}
// 验证是否是手机号码
function vailPhone(number) {
  let flag = true
  let myreg = /^(((13[0-9]{1})|(14[0-9]{1})|(17[0]{1})|(15[0-3]{1})|(15[5-9]{1})|(18[0-9]{1}))+\d{8})$/
  if (number.length !== 11 || !myreg.test(number)) {
    flag = false
  }
  return flag
}
// 验证是否西班牙手机(6开头 9位数)
function ifSpanish(number) {
  let flag = true
  let myreg = /^([6|7|9]{1}(\d+){8})$/
  if (number.length !== 9 || !myreg.test(number)) {
    flag = false
  }
  return flag
}
// 浮点型除法
function div(a, b) {
  let c, d, e, f
  try {
    e = a.toString().split('.')[1].length
  } catch (g) { }
  try {
    f = b.toString().split('.')[1].length
  } catch (g) {}
  // [eslint] Return statement should not contain assignment. (no-return-assign)
  c = Number(a.toString().replace('.', ''))
  d = Number(b.toString().replace('.', ''))
  return mul(c / d, Math.pow(10, f - e))
}
// 浮点型加法函数
function accAdd(arg1, arg2) {
  let r1, r2, m
  try {
    r1 = arg1.toString().split('.')[1].length
  } catch (e) {
    r1 = 0
  }
  try {
    r2 = arg2.toString().split('.')[1].length
  } catch (e) {
    r2 = 0
  }
  m = Math.pow(10, Math.max(r1, r2))
  return ((arg1 * m + arg2 * m) / m).toFixed(2)
}
// 浮点型乘法
function mul(a, b) {
  let c = 0
  let d = a.toString()
  let e = b.toString()
  try {
    c += a.toString().split('.')[1].length
  } catch (f) { }
  try {
    c += b.toString().split('.')[1].length
  } catch (f) { }
  return Number(d.replace('.', '')) * Number(e.replace('.', '')) / Math.pow(10, c)
}

//  遍历对象属性和值
function displayProp(obj) {
  let names = ''
  for (let name in obj) {
    names += name + obj[name]
  }
  return names
}
//  去除字符串所有空格
function sTrim(text) {
  return text.replace(/\s/g, '')
}
// 去除所有:,英文冒号
function replaceColon(txt) {
  return txt.replace(/:/g, '')
}
// 转换星星分数
function convertStarArray(score) {
  // 1 全星,0 空星,2半星
  let arr = []
  for (let i = 1; i <= 5; i++) {
    if (score >= i) {
      arr.push(1)
    } else if (score > i - 1 && score < i + 1) {
      arr.push(2)
    } else {
      arr.push(0)
    }
  }
  return arr
}
module.exports = {
  getCurrentTime: getCurrentTime,
  objLength: objLength,
  displayProp: displayProp,
  sTrim: sTrim,
  replaceColon: replaceColon,
  vailPhone: vailPhone,
  ifSpanish: ifSpanish,
  div: div,
  mul: mul,
  accAdd: accAdd,
  convertStarArray: convertStarArray,
  analysisUrl: analysisUrl,
  pageJump: pageJump,
  get: get
}
